import useSystemStore from '@/store/system';
import { getToken } from '@/store/user/utils';
import { joinUrl } from '@/utils/file/format';
import axios from 'axios';

type RequestParams = {
  params?: any;
  url: string;
  method: 'get' | 'put' | 'delete' | 'post';
  responseType?: any;
  data?: any;
};

export type RequestType = {
  controller: AbortController;
  path: string;
  id: string;
};
/* 取消请求列表 */
export const requestList = ref<RequestType[]>([]);

/**
 * @description: 上传，下载文件时的通用请求
 * @param {RequestParams} params
 */
export const requestFile = async (params: RequestParams) => {
  const http = axios.create();
  const sysStore = useSystemStore();

  const host = sysStore.$state.developer.baseURL;
  const token = getToken();
  http.defaults.withCredentials = true;

  const response = await http({
    method: params.method,
    url: joinUrl(host, params.url),
    responseType: params.responseType || 'blob',
    params: params.params,
    headers: {
      Authorization: `Bearer ${token}`,
    },
    onDownloadProgress: v => {
      // v
    },
    data: params.data,
    timeout: 0,
  });
  return response.data;
};
